import vue from '@vitejs/plugin-vue'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import Components from 'unplugin-vue-components/vite' //组件自动按需引入
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite' //自动导入 Composition API
import { visualizer } from 'rollup-plugin-visualizer' //打包size分析工具
import viteCompression from 'vite-plugin-compression' //使用 gzip 或者 brotli 来压缩资源
import vueSetupExtend from 'vite-plugin-vue-setup-extend' //vue3 setup语法糖默认是没有name属性的,使vue3语法糖支持name属性,在我们使用keep-alive的时候需要用到name
import { createHtmlPlugin } from 'vite-plugin-html' //输出env变量到html文件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' //生成 svg 雪碧图.
import { VueHooksPlusResolver } from '@vue-hooks-plus/resolvers'
import Unocss from 'unocss/vite'
import { presetAttributify, presetIcons, presetUno, transformerDirectives, transformerVariantGroup } from 'unocss'

import { PluginOption } from 'vite'
import path from 'path'

export function setupVitePlugins(env: EnvType.ImportMeta) {
	const plugins: PluginOption = [
		vue(),
		Components({
			extensions: ['vue', 'md'],
			include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
			resolvers: [
				ElementPlusResolver({
					importStyle: 'sass'
				}),
				IconsResolver()
			],
			dts: path.resolve(__dirname, '../components.d.ts')
		}),
		AutoImport({
			imports: ['vue', 'vue-router', 'pinia'],
			dts: path.resolve(__dirname, '../auto-import.d.ts'),
			resolvers: [VueHooksPlusResolver()],
			eslintrc: {
				enabled: true, // 已存在文件设置默认 false，需要更新时再打开，防止每次更新都重新生成
				filepath: path.resolve(__dirname, '../.eslintrc-auto-import.json'), // 生成文件地址和名称
				globalsPropValue: true
			}
		}),
		Icons({
			compiler: 'vue3',
			autoInstall: true
		}),
		visualizer(),
		viteCompression({
			verbose: true,
			disable: false,
			threshold: 10240,
			algorithm: 'gzip',
			ext: '.gz'
		}),
		vueSetupExtend(),
		createHtmlPlugin({
			inject: {
				data: { ...env }
			}
		}),

		Unocss({
			presets: [
				presetUno(),
				presetAttributify(),
				presetIcons({
					scale: 1.2,
					warn: true
				})
			],
			transformers: [transformerDirectives(), transformerVariantGroup()]
		}),
		createSvgIconsPlugin({
			// 指定需要缓存的图标文件夹
			iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
			// 指定symbolId格式
			symbolId: 'icon-[dir]-[name]'
		})
	]

	return plugins
}
